package com.part2.action.function;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.part2.action.common.upload.UploadProgressListener;
import com.part2.action.common.validator.Validator;
import com.part2.business.function.ProductsService;
import com.part2.Constants;

public class UserFileUploadAction extends DispatchAction {
	private final Log logger = LogFactory.getLog(getClass());

	private ProductsService productsService;

	public void setProductsService(ProductsService productsService) {
		this.productsService = productsService;
	}

	public ActionForward preUpload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String fileType = request.getParameter("fileType");
		if(Validator.isNotNull(fileType)){
			request.getSession().setAttribute("fileType", fileType);
		}
		return mapping.findForward("upload");
	}

	public ActionForward upload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Date date = new Date();
		UploadProgressListener pl = new UploadProgressListener(request);
		DiskFileUpload fu = new DiskFileUpload();
		fu.setProgressListener(pl);
		String fileType = (String) request.getSession().getAttribute("fileType");
//		System.out.println(">>>>>>>>>>>>>>>>>>>>"+fileType);
		String filePath = "";
		List items = fu.parseRequest(request);
		for (int i = 0; i < items.size(); i++) {
			FileItem fi = (FileItem) items.get(i);
			if (fi.isFormField()) {
			} else {
				if ("".equals(fi.getName().trim())) {
					continue;
				}
				// 文件名处理
				String filename = fi.getName();
				int pos = filename.lastIndexOf("\\");
				filename = filename.substring(pos + 1);
				String type = filename;
				SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmsss");
				int t = 0;

				// 找到上传文件的类型的位置，这个地方的是'.'
				t = filename.indexOf(".");
				type = type.substring(t);
				String times = f.format(date);
				// 组合成 time.type
				filename = times + type;
				if(fileType.equals("pic"))
				filePath = request.getSession().getServletContext()
						.getRealPath("/")
						+ Constants.PRO_UPLOAD_PIC_FILE_PATH;
				else 
					filePath = request.getSession().getServletContext()
					.getRealPath("/")
					+ Constants.PRO_UPLOAD_ATT_FILE_PATH;
				File fileDir = new File(filePath);
				if (!fileDir.exists())
					fileDir.mkdir();
				fi.write(new File(filePath + filename));
				request.setAttribute("uploadSuccess", true);
				request.setAttribute("uploadFileName", filename);
				request.setAttribute("fileType", fileType);
				return mapping.findForward("upload");
			}
		
		}

		return null;
	}

	public ActionForward downFile(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		OutputStream fos = null;
		InputStream fis = null;
		String file = request.getParameter("filaName");
		if (Validator.isNotNull(file)) {
			String fileDir = request.getSession().getServletContext()
					.getRealPath("/")
					+ Constants.PRO_UPLOAD_ATT_FILE_PATH;
			String filepath = fileDir + file;
			File downloadFile = new File(filepath);
			if (!downloadFile.exists()) {
				response.setContentType("text/html;charset=UTF-8"); 
				response
						.getWriter()
						.write(
								"<script language='javascript'>alert('"+"对不起,文件不存在!"+"');history.go(-1); </script>");
			} else {
				try{
				fis = new FileInputStream(downloadFile);
				bis = new BufferedInputStream(fis);
				fos = response.getOutputStream();
				bos = new BufferedOutputStream(fos);
				response.setHeader("Content-disposition",
						"attachment;filename="
								+ URLEncoder.encode(file, "utf-8"));
					int bytesRead = 0;
					byte[] buffer = new byte[8192];
					while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
						bos.write(buffer, 0, bytesRead);
					}
				}catch(IOException dd){
					fis.close();bis.close();
					fos.close();bos.close();
					return null;
					}
				bos.flush();
				fis.close();
				bis.close();
				fos.close();
				bos.close();
			}
		}
		return null;
	}
}
